package com.zjw.algorithm.utils;

import java.util.Arrays;

public class MathUtils {

    public static void main(String[] args) {
//        System.out.println(pow(2.00000, -2));
        System.out.println(Double.MAX_VALUE);
        System.out.println(pow(1e121, 12));
    }

    /**
     * 快速幂算法
     */
    public static long pow(long num, int pow) {
        long result = 1;

        long ret = num;

        while (pow != 0) {
            if ((pow & 1) == 1) {
                result = result * ret;
            }

            pow >>= 1;
            ret = ret * ret;
        }

        return result;
    }

    public static double pow(double num, int pow) {
        if (pow == 0) {
            return 1.0;
        }

        if (num == 1.0) {
            return 1.0;
        }

        if (pow == -1) {
            return 1 / num;
        }


        double result = 1;

        boolean isNegative = pow < 0;
        boolean needReOnce = false;
        pow = Math.abs(pow);
        double ret = num;

        if (pow == Integer.MIN_VALUE) {
            pow = Integer.MAX_VALUE;
            needReOnce = true;
        }

        while (pow != 0) {
            if ((pow & 1) == 1) {
                result = result * ret;
            }

            pow >>= 1;
            ret = ret * ret;
        }

        if (needReOnce) {
            result *= num;
        }

        return isNegative ? 1 / result : result;
    }
}
